/**
 * 后续不再维护。请替换为VxeTableListMixin
 *
 * 新增修改完成调用 modalFormOk方法 编辑弹框组件ref定义为modalForm
 * 高级查询按钮调用 superQuery方法  高级查询组件ref定义为superQueryModal
 * data中url定义 list为查询列表  delete为删除单条记录  deleteBatch为批量删除
 *
 */
import { filterObj, downloadFile } from '@/utils/util'
import { deleteAction, getAction, postAction } from '@/services/manage'
import { downFile } from '@/services/common'
import Criteria from '@/utils/criteria'
import { OPERATOR } from '@/store/mutation-types'
import { checkPermi, checkRole } from '@/utils/auth'
export const VxeTableMixin = {
  data() {
    return {
      queryParam: {},
      // tableToolbar: {
      //   refresh: {
      //     query: () => {
      //       this.onClearSelected()
      //       this.loadData(1)
      //     }
      //   },
      //   tools: [],
      //   perfect: true,
      //   print: false,
      //   zoom: true,
      //   custom: true,
      //   slots: { },
      //   'class-name': 'z-vxe-toolbar'// 自定义table样式使用
      // },
      height: 400,
      /* 数据源 */
      dataSource: [],
      /* 分页参数 */
      ipagination: {
        total: 0,
        currentPage: 1,
        pageSize: 10
      },
      /* 排序参数 */
      isorter: {
        fieldName: 'createTime',
        desc: true
      },
      /* 筛选参数 */
      filters: {},
      /* table加载状态 */
      loading: false,
      /* table选中keys*/
      selectedRowKeys: [],
      /* table选中records*/
      selectionRows: [],
      /* 查询折叠 */
      toggleSearchStatus: false,
      /* 高级查询条件 */
      superQueryParams: '',
      labelCol: { span: 5 },
      wrapperCol: { span: 18 },
      listeners: {
        'sort-change': this.sortChange,
        'checkbox-change': this.onSelectChange,
        'checkbox-all': this.onSelectChange,
        'page-change': this.handlePageChange
      },
      importTemplateCode: '', // 导入模板编码
      closeMessage: ''
    }
  },
  computed: {
    getToolbarConfig() { // 不需要tool时，页面设置toolbarConfig="{}"
      const toolbar = this.getToolbarByAuth()
      const exportComp = this.getExportComponent()
      exportComp && toolbar.tools.unshift(exportComp)
      const toolbarConfig = {
        refresh: {
          query: () => {
            this.onClearSelected()
            this.loadData(1)
          }
        },
        zoom: true,
        custom: true,
        perfect: true,
        import: this.hasAuth('add'),
        slots: {},
        buttons: toolbar.buttons,
        tools: toolbar.tools,
        'class-name': 'z-vxe-toolbar'
      }
      return Object.assign({}, toolbarConfig, this.toolbarConfig || {})
    },
    options() {
      /*
       *customTableToolbar为页面需要自定义的toolbar配置
       *也可以直接在页面组件使用时直接定义属性覆盖该配置
       */
      const toolbarConfig = Object.assign({}, this.getToolbarConfig, this.customTableToolbar)
      return {
        customConfig: { storage: { visible: true, resizable: true }},
        rowConfig: { keyField: 'id' },
        loading: this.loading,
        height: this.height,
        // emptyText: this.hasAuthTable ? '暂无数据' : '无访问权限，请联系管理员',
        toolbarConfig: toolbarConfig,
        columns: this.columns || [],
        data: this.dataSource || [],
        pagerConfig: {
          ...this.ipagination,
          layouts: ['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'PageCount', 'Total']
        },
        sortConfig: { trigger: 'cell', remote: true },
        exportConfig: {
          remote: true,
          type: 'xls',
          exportMethod: ({ options }) => {
            this.handleExportXls(options.filename)
          }
        },
        importConfig: {
          remote: true,
          types: ['xls', 'xlsx'],
          importMethod: ({ file, options }) => {
            this.handleImportXls({ file, options })
          }
        }
      }
    }
  },
  created() {
    this.initAuth && this.initAuth()
    if (!this.disableMixinCreated) {
      this.loadData()
    }
  },
  mounted() {
    setTimeout(() => {
      this.setTableHeight()
    }, 100)
  },
  methods: {
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      // if (!this.hasAuthTable) { // 无数据权限，不请求
      //   this.dataSource = []
      //   return
      // }
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.currentPage = 1
      }
      var params = this.getQueryParams()// 查询条件
      this.loading = true
      return getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.result.content || res.result
          this.ipagination.total = res.result.totalElements
        }
        // else {
        //   this.$message.warning(res.message)
        // }
      }).finally(() => {
        this.loading = false
      })
    },
    handleSuperQuery(params) {
      // 高级查询方法
      if (!params) {
        this.superQueryParams = ''
      } else {
        this.superQueryParams = params
      }
      this.onClearSelected()
      this.loadData(1)
    },
    getQueryParams() {
      // 获取查询条件
      const queryParam = new Criteria()
      queryParam.addCriterions(Object.assign({}, filterObj(this.queryParam), this.filters), OPERATOR.LIKE_START)// 过滤参数转换为jpa支持格式
      if (this.superQueryParams) {
        queryParam.concatCriterions(this.superQueryParams)
      }
      this.isorter && queryParam.addOrder(this.isorter)// 增加排序规则
      var param = Object.assign({}, { criteria: queryParam.getEncode() })
      // param.field = this.getQueryField()
      param.pageNo = this.ipagination.currentPage
      param.pageSize = this.ipagination.pageSize
      return filterObj(param)
    },
    getQueryField() {
      // TODO 字段权限控制
      var str = 'id,'
      this.columns.forEach(function(value) {
        if (value.field) {
          str += ',' + value.field
        }
      })
      return str
    },
    onSelectChange({ records, checked }) {
      this.selectedRowKeys = []
      records.forEach(item => {
        const rowId = this.$refs.vxeTable.getRowid(item)
        this.selectedRowKeys.push(rowId)
      })
      this.selectionRows = records
    },
    onClearSelected() {
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    searchQuery() {
      this.onClearSelected()
      this.loadData(1)
    },
    superQuery() {
      this.$refs.superQueryModal.show()
    },
    searchReset() {
      this.onClearSelected()
      this.queryParam = {}
      this.loadData(1)
    },
    async batchDel() {
      if (!this.url.deleteBatch) {
        this.$message.error('请设置url.deleteBatch属性!')
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return
      } else {
        if (typeof this.batchDelBefore === 'function') {
          // 批量删除之前执行判断，是否能删除,支持异步
          const message = await this.batchDelBefore()
          if (message) {
            return this.$message.warning(message)
          }
        }
        this.$confirm({
          title: '确认删除',
          content: '是否删除选中数据?',
          onOk: () => {
            this.loading = true
            deleteAction(`${this.url.deleteBatch}${this.selectedRowKeys.join()}`).then((res) => {
              if (res.success) {
                this.$message.success(res.message)
                this.loadData()
                this.onClearSelected()
              }
              // else {
              //   this.$message.warning(res.message)
              // }
            }).finally(() => {
              this.loading = false
            })
          }
        })
      }
    },
    async handleDelete(id) {
      if (!this.url.delete) {
        this.$message.error('请设置url.delete属性!')
        return
      }
      if (typeof this.deleteBefore === 'function') {
        // 批量删除之前执行判断，是否能删除,支持异步
        const message = await this.deleteBefore()
        if (message) {
          return this.$message.warning(message)
        }
      }
      deleteAction(`${this.url.delete}${id}`).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.loadData()
        }
        // else {
        // this.$message.warning(res.message)
        // }
      })
    },
    async handleEdit(record) {
      if (typeof this.editBefore === 'function') {
        // 批量删除之前执行判断，是否能删除,支持异步
        const message = await this.editBefore()
        if (message) {
          return this.$message.warning(message)
        }
      }
      this.$refs.modalForm.edit({ ...record })
      this.$refs.modalForm.title = '编辑'
      this.$refs.modalForm.disableSubmit = false
    },
    handleAdd: function() {
      this.$refs.modalForm.add()
      this.$refs.modalForm.title = '新增'
      this.$refs.modalForm.disableSubmit = false
    },
    handleToggleSearch() {
      this.toggleSearchStatus = !this.toggleSearchStatus
    },
    modalFormOk() {
      // 新增/修改 成功时，重载列表
      this.loadData()
    },
    handleDetail: function(record) {
      this.$refs.modalForm.disableSubmit = true
      this.$refs.modalForm.edit(record)
      this.$refs.modalForm.title = '详情'
    },
    handleExportXls(code, fileName) { // 导出
      if (this.closeMessage) {
        return
      }
      this.closeMessage = this.$message.loading('下载中..', 0)
      const param = this.getQueryParams()
      param.pageNo = 1
      param.pageSize = this.ipagination.total + 999
      const type = this.options.exportConfig.type || 'xls'
      downFile(`excel/export/download/${type}/${code}`, param, { _allResponse: true }).then((res) => {
        this.closeMessage()
        const { data, headers } = res
        this.closeMessage = ''
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        // downloadFile(data, fileName + '.' + type)
        var fileName = decodeURIComponent(headers['content-disposition'].split(';')[1].split('filename=')[1])
        downloadFile(data, fileName.slice(1, fileName.length - 1))
      })
    },
    getExportElementId() { // 获取导出标识，后续导出组件根据改标识请求导出模板
      if (this.elementId) { // 可以直接在组件data内指定
        return this.elementId
      }
      if (!this.auth) {
        return
      }
      if (this.auth['permi'] && this.auth['permi'].export) { // 可以与权限标识放一起
        return this.auth['permi'].export
      }
      if (this.auth['role'] && this.auth['role'].export) {
        return this.auth['role'].export
      }
      return
    },
    getExportComponent() { // 判断是否需要导出组件
      if ((!this.toolbarConfig || this.toolbarConfig.export !== false) && this.hasAuth('export')) {
        const elementId = this.getExportElementId()
        return { toolRender: { name: 'VxeToolbarExport', props: { icon: 'download', shape: 'circle', elementId: elementId }, events: { click: this.handleExportXls }}}
      }
    },
    handleImportXls({ file, options }) { // 页面表格导入
      if (this.closeMessage) {
        return
      }
      if (!this.importTemplateCode) { // importTemplateCode为导入管理模块对应导入模板编码
        return this.$message.warning('请先设置导入模板编码')
      }
      this.closeMessage = this.$message.loading('上传中..', 0)
      const formData = new FormData()
      formData.append('file', file)
      postAction(`/excel/import/upload/${this.importTemplateCode}`, formData, { timeout: 60000 }).then(res => {
        if (res.success) {
          this.loadData()
          this.$message.success(res.message)
        }
      }).finally(() => {
        this.closeMessage()
        this.closeMessage = ''
      })
    },
    handlePageChange({ currentPage, pageSize }) {
      this.ipagination.currentPage = currentPage
      this.ipagination.pageSize = pageSize
      this.loadData()
    },
    setTableHeight() { // 设置页面表格高度
      if (this.$refs.vxeTable) {
        const clientHeight = document.documentElement.clientHeight
        const tableTop = this.$refs.vxeTable.$el.getBoundingClientRect().top
        this.height = clientHeight - tableTop - 40
      }
    },
    sortChange({ property, order }) { // 页面表格排序
      this.isorter = {
        fieldName: property,
        desc: order === 'desc'
      }
      this.loadData()
    },
    getToolbarByAuth() { // 获取有权限的toolbar功能
      const buttons = []; const tools = []
      // 因部分页面新增、编辑使用相同接口。权限控制时也需要一起控制
      // 新增、编辑使用同一个标识控制时，使用save标识，分开控制时使用add、edit标识
      // const saveKey = this.hasAuthKey('save') ? 'save' : 'add'
      this.hasAuth('add') && buttons.push({ buttonRender: { name: 'VxeToolbarAdd', events: { click: this.handleAdd }}})
      // 因部分页面删除、批量删除使用相同接口。权限控制时也需要一起控制
      // 删除、批量删除使用同一个标识控制时，使用remove标识，分开控制时使用delete、deleteBatch标识
      // const removeKey = this.hasAuthKey('remove') ? 'remove' : 'deleteBatch'
      // this.hasAuth(removeKey) && buttons.push({ buttonRender: { name: 'VxeToolbarBatchDel', events: { click: this.batchDel }}})
      this.hasAuth('deleteBatch') && buttons.push({ buttonRender: { name: 'VxeToolbarBatchDel', events: { click: this.batchDel }}})
      return {
        buttons,
        tools
      }
    },
    hasAuth(type) { // 判断是否有权限
      if (!this.auth) {
        return true
      }
      if (this.auth['permi']) {
        return !this.auth['permi'][type] || checkPermi(this.auth['permi'][type])
      }
      return !this.auth['role'][type] || checkRole(this.auth['role'][type])
    }
    // initAuth() { // 初始化权限标识
    //   /**
    //     *  auth:{ //格式为
    //     *    permi:{
    //     *       add:'' || [],//新增
    //     *       edit:[] || '',//编辑
    //     *       save:[] || '',//新增、编辑同时控制
    //     *       deleteBatch:'' || [],//批量删除
    //     *       delete:'' || [],//删除
    //     *       remove:[] || '',新增、编辑同时控制
    //     *       import:'' || [],//导入
    //     *       export:'' || [],//导出
    //     *       table:'' || [],//列表
    //     *     },
    //     *    role:{} //参数与permi相同，后台暂时未实现
    //     *  }
    //   */
    //   const name = this.$options.name
    //   this.auth = {
    //     permi: {
    //       table: `${name}:table`, // 表格数据权限
    //       add: `${name}:add`, // 新增权限
    //       edit: `${name}:edit`, // 编辑权限
    //       delete: `${name}:delete`, // 删除权限
    //       deleteBatch: `${name}:deleteBatch`, // 批量权限
    //       import: `${name}:import`, // 导入权限
    //       export: `${name}:export`// 导出权限
    //     }
    //   }
    // },
    // hasAuthKey(key) { // 判断权限标识对象内是否有该标识
    //   if (!this.auth) {
    //     return false
    //   }
    //   return (this.auth['permi'] && this.auth.permi[key]) || (this.auth['role'] && this.auth.role[key])
    // },

  }
}

